<!DOCTYPE html>
<html  lang="zh-CN" >
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="theme-color" content="#fff" id="theme-color">
  <meta name="description" content="深山磨柴斧，一鸣震江湖">
  <link rel="icon" href="/img/ic_head.jpg">
  <title>WebView完整配置及正确使用，抠门式的内存管控</title>
  
  
  <meta property="og:title" content="WebView完整配置及正确使用，抠门式的内存管控">
  
  
  <meta property="og:url" content="http://example.com/2020/12/03/WebView%E5%AE%8C%E6%95%B4%E9%85%8D%E7%BD%AE%E5%8F%8A%E6%AD%A3%E7%A1%AE%E4%BD%BF%E7%94%A8%EF%BC%8C%E6%8A%A0%E9%97%A8%E5%BC%8F%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E6%8E%A7/index.html">
  
  
  <meta property="og:img" content="/img/ic_head.jpg">
  
  
  <meta property="og:img" content="深山磨柴斧，一鸣震江湖">
  
  
  <meta property="og:type" content="article">
  <meta property="og:article:published_time" content="2020-12-03">
  <meta property="og:article:modified_time" content="2021-04-14">
  <meta property="og:article:author" content="Cupster">
  
  
  <meta property="og:article:tag" content="WebView">
  
  <meta property="og:article:tag" content="JavaScript">
  
  <meta property="og:article:tag" content="JsBridge">
  
  
  
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
    var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
      }
    };
    setDarkmode();
  </script>
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
  </script>
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  
  <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
  <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
  <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
  
  
<link rel="stylesheet" href="/css/main.css">

  
  
<link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">

  
  
<link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">

  
  
<link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">

  
  
  
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <div class="wrapper">
    
    <nav class="navbar">
  <div class="navbar-logo">
    <span class="navbar-logo-main">
      
      <img class="navbar-logo-img" src="/img/ic_head.jpg" alt="logo">
      
      <span class="navbar-logo-dsc">不负明天</span>
    </span>
  </div>
  <div class="navbar-menu">
    
    <a href="/" class="navbar-menu-item">
    
    首页
    
    </a>
    
    <a href="/archives" class="navbar-menu-item">
    
    归档
    
    </a>
    
    <a href="/tags" class="navbar-menu-item">
    
    标签
    
    </a>
    
    <a href="/categories" class="navbar-menu-item">
    
    分类
    
    </a>
    
    <a href="/about" class="navbar-menu-item">
    
    关于
    
    </a>
    
    <a href="/links" class="navbar-menu-item">
    
    友链
    
    </a>
    
    <a class="navbar-menu-item darknavbar" id="dark"><i class="iconfont icon-weather"></i></a>
    <a class="navbar-menu-item searchnavbar" id="search"><i class="iconfont icon-search" style="font-size: 1.2rem; font-weight: 400;"></i></a>
  </div>
</nav>
    
    <div id="local-search" style="display: none;">
      <input class="navbar-menu-item" id="search-input" placeholder="请输入搜索内容...">
      <div id="search-content"></div>
    </div>
    
    <div class="section-wrap">
      <div class="container">
        <div class="columns">
          <main class="main-column">
<article class="card card-content">
  <header>
    <h1 class="post-title">
      WebView完整配置及正确使用，抠门式的内存管控
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2020-12-03T04:25:21.000Z">
      <i class="iconfont icon-calendar" style="margin-right: 2px;"></i>
      <span>2020-12-03</span>
    </time>
    
    <span class="dot"></span>
    
    <a href="/categories/Android/" class="post-meta-link">Android</a>
    
    
    
    <span class="dot"></span>
    <span>2.2k 字</span>
    
  </div>
  
  <div class="post-meta post-show-meta" style="margin-top: -10px;">
    <div style="display: flex; align-items: center;">
      <i class="iconfont icon-biaoqian" style="margin-right: 2px; font-size: 1.15rem;"></i>
      
      
        <a href="/tags/WebView/" class="post-meta-link">WebView</a>
      
      
      <span class="dot"></span>
      
        <a href="/tags/JavaScript/" class="post-meta-link">JavaScript</a>
      
      
      <span class="dot"></span>
      
        <a href="/tags/JsBridge/" class="post-meta-link">JsBridge</a>
      
    </div>
  </div>
  
  </header>
  <div id="section" class="post-content">
    <hr>
<h1 id="1-要点"><a href="#1-要点" class="headerlink" title="1.要点"></a>1.要点</h1><ol>
<li>一个可视为浏览器的View</li>
<li>用于加载html页面及处理交互</li>
<li>重量级View，建议在代码中添加至布局<kbd>内存角度</kbd></li>
<li>建议至于独立Activity且占满</li>
</ol>
<h1 id="2-使用"><a href="#2-使用" class="headerlink" title="2.使用"></a>2.使用</h1><h4 id="2-1布局文件"><a href="#2-1布局文件" class="headerlink" title="2.1布局文件"></a>2.1布局文件</h4><pre><code>不在布局文件中直接引入使用，使用java代码添加WebView,便于管控其生命周期
</code></pre>
<pre class="highlight"><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">LinearLayout</span> <span class="attr">xmlns:android</span>=<span class="string">&quot;http://schemas.android.com/apk/res/android&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">&quot;match_parent&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">&quot;match_parent&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:orientation</span>=<span class="string">&quot;vertical&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    &lt;include</span><br><span class="line">        layout=&quot;@layout/app_toolbar_base&quot;</span><br><span class="line">         /&gt;</span><br><span class="line">    &lt;LinearLayout</span><br><span class="line">        android:id=&quot;@+id/h5_content_layout&quot;</span><br><span class="line">        android:orientation=&quot;vertical&quot;</span><br><span class="line">        android:layout_width=&quot;match_parent&quot;</span><br><span class="line">        android:layout_height=&quot;match_parent&quot;</span><br><span class="line">        android:paddingTop=&quot;8dp&quot;</span><br><span class="line">        &gt;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">LinearLayout</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">LinearLayout</span>&gt;</span></span><br></pre>
<h4 id="2-2Java代码添加WebView"><a href="#2-2Java代码添加WebView" class="headerlink" title="2.2Java代码添加WebView"></a>2.2Java代码添加WebView</h4><pre class="highlight"><span class="line"><span class="comment">//</span></span><br><span class="line">LinearLayout mContentLayout;</span><br><span class="line">WebView mWebView;</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(<span class="meta">@Nullable</span> Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">    </span><br><span class="line">    setContentView(R.layout.activity_h5);</span><br><span class="line">    initToolbar();</span><br><span class="line">    initView();<span class="comment">//初始化控件</span></span><br><span class="line">    initData();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    mContentLayout = findViewById(R.id.h5_content_layout);</span><br><span class="line">    LinearLayout.LayoutParams params = <span class="keyword">new</span> LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);</span><br><span class="line">    <span class="comment">//代码中添加WebView</span></span><br><span class="line">    mWebView = <span class="keyword">new</span> WebView(<span class="keyword">this</span>.getApplicationContext());</span><br><span class="line">    mWebView.setLayoutParams(params);</span><br><span class="line">    mContentLayout.addView(mWebView);</span><br><span class="line">    <span class="comment">//配置WebView</span></span><br><span class="line">    buildWebView();</span><br><span class="line">&#125;</span><br></pre>

<h4 id="2-3-控制生命周期，防止内存泄漏"><a href="#2-3-控制生命周期，防止内存泄漏" class="headerlink" title="2.3 控制生命周期，防止内存泄漏"></a>2.3 控制生命周期，防止内存泄漏</h4><pre class="highlight"><span class="line"><span class="comment">//</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onNewIntent</span><span class="params">(Intent intent)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onNewIntent(intent);</span><br><span class="line">        setIntent(intent);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@SuppressLint(&quot;SetJavaScriptEnabled&quot;)</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onResume</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume();</span><br><span class="line">        mWebView.getSettings().setJavaScriptEnabled(<span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPause</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        dismissLoading();</span><br><span class="line">        mWebView.getSettings().setJavaScriptEnabled(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">super</span>.onPause();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDestroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        destoryWebView();</span><br><span class="line">        dismissLoading();</span><br><span class="line">        <span class="keyword">super</span>.onDestroy();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">destoryWebView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (mWebView != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//加载空页面，并清理缓存、历史</span></span><br><span class="line">            mWebView.loadDataWithBaseURL(<span class="keyword">null</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;text/html&quot;</span>, <span class="string">&quot;utf-8&quot;</span>, <span class="keyword">null</span>);</span><br><span class="line">            mWebView.clearHistory();</span><br><span class="line">            mWebView.clearCache(<span class="keyword">true</span>);</span><br><span class="line">            <span class="comment">//移除、释放</span></span><br><span class="line">            ((ViewGroup) mWebView.getParent()).removeView(mWebView);</span><br><span class="line">            mWebView.destroy();</span><br><span class="line">            mWebView = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dismissLoading</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br></pre>
<h4 id="2-4-重点：WebView-配置"><a href="#2-4-重点：WebView-配置" class="headerlink" title="2.4 重点：WebView 配置"></a>2.4 重点：WebView 配置</h4><pre class="highlight"><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">buildWebView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    mWebView.setWebChromeClient(<span class="keyword">new</span> WebChromeClient()&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedTitle</span><span class="params">(WebView view, String title)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (!TextUtils.isEmpty(title))&#123;</span><br><span class="line">                <span class="keyword">if</span> (title.length()&lt;<span class="number">6</span>)&#123;</span><br><span class="line">                    mToolbarTitle.setText(title);</span><br><span class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span> (title.length()&gt;<span class="number">10</span>)&#123;</span><br><span class="line">                    mToolbarTitle.setTextSize(<span class="number">12f</span>);</span><br><span class="line">                    title = title.substring(<span class="number">0</span>,<span class="number">8</span>);</span><br><span class="line">                    title = title + <span class="string">&quot;...&quot;</span>;</span><br><span class="line">                    mToolbarTitle.setText(title);</span><br><span class="line">                &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                    mToolbarTitle.setTextSize(<span class="number">14f</span>);</span><br><span class="line">                    mToolbarTitle.setText(title);</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) &#123;</span><br><span class="line">        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);</span><br><span class="line">        mWebView.setWebViewClient(<span class="keyword">new</span> WebViewClient() &#123;</span><br><span class="line">            <span class="meta">@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, WebResourceRequest request)</span> </span>&#123;</span><br><span class="line">                view.loadUrl(String.valueOf(request.getUrl()), request.getRequestHeaders());</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedSslError</span><span class="params">(WebView view, SslErrorHandler handler, SslError error)</span> </span>&#123;</span><br><span class="line">                handler.proceed();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageStarted</span><span class="params">(WebView view, String url, Bitmap favicon)</span> </span>&#123;</span><br><span class="line">                showLoading();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageFinished</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                dismissLoading();</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        mWebView.setWebViewClient(<span class="keyword">new</span> WebViewClient() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                view.loadUrl(url);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedSslError</span><span class="params">(WebView view, SslErrorHandler handler, SslError error)</span> </span>&#123;</span><br><span class="line">                handler.proceed();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageStarted</span><span class="params">(WebView view, String url, Bitmap favicon)</span> </span>&#123;</span><br><span class="line">                showLoading();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageFinished</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                dismissLoading();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置</span></span><br><span class="line">    WebSettings webSettings = mWebView.getSettings();</span><br><span class="line">    <span class="comment">//设置支持Javascript</span></span><br><span class="line">    webSettings.setJavaScriptEnabled(<span class="keyword">true</span>);</span><br><span class="line">    <span class="comment">//设置自适应</span></span><br><span class="line">    webSettings.setUseWideViewPort(<span class="keyword">true</span>); <span class="comment">//将图片调整到适合webview的大小</span></span><br><span class="line">    webSettings.setLoadWithOverviewMode(<span class="keyword">true</span>); <span class="comment">// 缩放至屏幕的大小</span></span><br><span class="line">    <span class="comment">//缩放</span></span><br><span class="line">    webSettings.setSupportZoom(<span class="keyword">true</span>); <span class="comment">//支持缩放，默认为true。是setBuiltInZoomControls(true)的前提。</span></span><br><span class="line">    webSettings.setBuiltInZoomControls(<span class="keyword">true</span>); <span class="comment">//设置内置的缩放控件。若为false=不可缩放</span></span><br><span class="line">    webSettings.setDisplayZoomControls(<span class="keyword">false</span>); <span class="comment">//隐藏原生的缩放控件</span></span><br><span class="line">    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); </span><br><span class="line">    <span class="comment">//缓存模式如下：</span></span><br><span class="line">    <span class="comment">//LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据</span></span><br><span class="line">    <span class="comment">//LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。</span></span><br><span class="line">    <span class="comment">//LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.</span></span><br><span class="line">    <span class="comment">//LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。</span></span><br><span class="line">    webSettings.setAllowFileAccess(<span class="keyword">true</span>);<span class="comment">//可以访问文件</span></span><br><span class="line">    webSettings.setDomStorageEnabled(<span class="keyword">true</span>);<span class="comment">// 开启DOM storage</span></span><br><span class="line">    webSettings.setDatabaseEnabled(<span class="keyword">true</span>);<span class="comment">//开启database storage</span></span><br><span class="line">    webSettings.setAppCacheEnabled(<span class="keyword">true</span>);<span class="comment">//开启Application Caches</span></span><br><span class="line">    </span><br><span class="line">    String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;</span><br><span class="line">    webSettings.setAppCachePath(cacheDirPath);<span class="comment">//设置Caches缓存目录</span></span><br><span class="line">    <span class="comment">//每个 Application 只调用一次 WebSettings.setAppCachePath()，WebSettings.setAppCacheMaxSize()</span></span><br><span class="line">    webSettings.setJavaScriptCanOpenWindowsAutomatically(<span class="keyword">true</span>); <span class="comment">//通过JS打开新窗口</span></span><br><span class="line">    webSettings.setLoadsImagesAutomatically(<span class="keyword">true</span>); <span class="comment">//自动加载图片</span></span><br><span class="line">    webSettings.setDefaultTextEncodingName(<span class="string">&quot;utf-8&quot;</span>);<span class="comment">//设置编码格式</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre>


<h1 id="3-其他细节代码"><a href="#3-其他细节代码" class="headerlink" title="3.其他细节代码"></a>3.其他细节代码</h1><blockquote>
<p><strong>载入页面</strong></p>
</blockquote>
<pre class="highlight"><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">loadH5</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (TextUtils.isEmpty(mUrlStr))&#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//先清理，后载入，减小内存占用</span></span><br><span class="line">    mWebView.loadDataWithBaseURL(<span class="keyword">null</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;text/html&quot;</span>, <span class="string">&quot;utf-8&quot;</span>, <span class="keyword">null</span>);</span><br><span class="line">    mWebView.clearHistory();</span><br><span class="line">    mWebView.clearCache(<span class="keyword">true</span>);</span><br><span class="line">    mWebView.loadUrl(mUrlStr);</span><br><span class="line">&#125;</span><br></pre>

<blockquote>
<p><strong>AndroidManifest.xml声明权限</strong></p>
</blockquote>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">&quot;android.permission.INTERNET&quot;</span>/&gt;</span></span><br></pre>
<blockquote>
<p><strong>AndroidManifest.xml声明H5Activity</strong></p>
</blockquote>
<pre class="highlight"><span class="line">&lt;activity</span><br><span class="line">android:name=&quot;.H5Activity&quot;</span><br><span class="line">android:screenOrientation=&quot;portrait&quot; /&gt;</span><br></pre>
<blockquote>
<p><strong>res/values/style.xml</strong></p>
</blockquote>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">name</span>=<span class="string">&quot;AppTheme&quot;</span> <span class="attr">parent</span>=<span class="string">&quot;Theme.AppCompat.Light.NoActionBar&quot;</span>&gt;</span></span><br><span class="line"><span class="xml">        <span class="comment">&lt;!-- Customize your theme here. --&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">item</span> <span class="attr">name</span>=<span class="string">&quot;colorPrimary&quot;</span>&gt;</span>@color/colorPrimary<span class="tag">&lt;/<span class="name">item</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">item</span> <span class="attr">name</span>=<span class="string">&quot;colorPrimaryDark&quot;</span>&gt;</span>@color/colorPrimaryDark<span class="tag">&lt;/<span class="name">item</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">item</span> <span class="attr">name</span>=<span class="string">&quot;colorAccent&quot;</span>&gt;</span>@color/colorAccent<span class="tag">&lt;/<span class="name">item</span>&gt;</span></span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre>


<h1 id="4-完整Activity代码"><a href="#4-完整Activity代码" class="headerlink" title="4.完整Activity代码"></a>4.完整Activity代码</h1><pre class="highlight"><span class="line"><span class="keyword">package</span> com.cupster.webview;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> android.annotation.SuppressLint;</span><br><span class="line"><span class="keyword">import</span> android.app.Activity;</span><br><span class="line"><span class="keyword">import</span> android.content.Context;</span><br><span class="line"><span class="keyword">import</span> android.content.Intent;</span><br><span class="line"><span class="keyword">import</span> android.graphics.Bitmap;</span><br><span class="line"><span class="keyword">import</span> android.graphics.Color;</span><br><span class="line"><span class="keyword">import</span> android.net.http.SslError;</span><br><span class="line"><span class="keyword">import</span> android.os.Build;</span><br><span class="line"><span class="keyword">import</span> android.os.Bundle;</span><br><span class="line"><span class="keyword">import</span> android.support.annotation.Nullable;</span><br><span class="line"><span class="keyword">import</span> android.support.annotation.RequiresApi;</span><br><span class="line"><span class="keyword">import</span> android.support.v7.app.AppCompatActivity;</span><br><span class="line"><span class="keyword">import</span> android.support.v7.widget.Toolbar;</span><br><span class="line"><span class="keyword">import</span> android.text.TextUtils;</span><br><span class="line"><span class="keyword">import</span> android.util.Log;</span><br><span class="line"><span class="keyword">import</span> android.view.KeyEvent;</span><br><span class="line"><span class="keyword">import</span> android.view.View;</span><br><span class="line"><span class="keyword">import</span> android.view.ViewGroup;</span><br><span class="line"><span class="keyword">import</span> android.webkit.SslErrorHandler;</span><br><span class="line"><span class="keyword">import</span> android.webkit.WebChromeClient;</span><br><span class="line"><span class="keyword">import</span> android.webkit.WebResourceRequest;</span><br><span class="line"><span class="keyword">import</span> android.webkit.WebSettings;</span><br><span class="line"><span class="keyword">import</span> android.webkit.WebView;</span><br><span class="line"><span class="keyword">import</span> android.webkit.WebViewClient;</span><br><span class="line"><span class="keyword">import</span> android.widget.ImageView;</span><br><span class="line"><span class="keyword">import</span> android.widget.LinearLayout;</span><br><span class="line"><span class="keyword">import</span> android.widget.TextView;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> android.view.KeyEvent.KEYCODE_BACK;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">H5Activity</span> <span class="keyword">extends</span> <span class="title">AppCompatActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">&quot;H5Activity&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String APP_CACAHE_DIRNAME = <span class="string">&quot;/didigoweb&quot;</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String KEY_H5_URL = <span class="string">&quot;H5_URL&quot;</span>;</span><br><span class="line"></span><br><span class="line">    TextView mToolbarTitle;</span><br><span class="line">    LinearLayout mContentLayout;</span><br><span class="line">    WebView mWebView;</span><br><span class="line">    String mUrlStr;</span><br><span class="line">    <span class="keyword">boolean</span> isCanScale  = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">open</span><span class="params">(Context context , String url)</span></span>&#123;</span><br><span class="line">        Intent intent = <span class="keyword">new</span> Intent(context , H5Activity.class);</span><br><span class="line">        intent.putExtra(KEY_H5_URL ,url);</span><br><span class="line">        context.startActivity(intent);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(<span class="meta">@Nullable</span> Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) &#123;</span><br><span class="line">            View decorView = getWindow().getDecorView();</span><br><span class="line">            <span class="keyword">int</span> option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN</span><br><span class="line">                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;</span><br><span class="line">            decorView.setSystemUiVisibility(option);</span><br><span class="line">            getWindow().setStatusBarColor(Color.WHITE);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        setAndroidNativeLightStatusBar(<span class="keyword">this</span>, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">        setContentView(R.layout.activity_h5);</span><br><span class="line">        initToolbar();</span><br><span class="line">        initView();</span><br><span class="line">        initData();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressLint(&quot;SetJavaScriptEnabled&quot;)</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onResume</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume();</span><br><span class="line">        mWebView.getSettings().setJavaScriptEnabled(<span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPause</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        dismissLoading();</span><br><span class="line">        mWebView.getSettings().setJavaScriptEnabled(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">super</span>.onPause();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDestroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        destoryWebView();</span><br><span class="line">        dismissLoading();</span><br><span class="line">        <span class="keyword">super</span>.onDestroy();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onNewIntent</span><span class="params">(Intent intent)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onNewIntent(intent);</span><br><span class="line">        setIntent(intent);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onKeyDown</span><span class="params">(<span class="keyword">int</span> keyCode, KeyEvent event)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ((keyCode == KEYCODE_BACK) &amp;&amp; mWebView.canGoBack()) &#123;</span><br><span class="line">            finish();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.onKeyDown(keyCode, event);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initToolbar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Toolbar toolbar = findViewById(R.id.toolbar);</span><br><span class="line">        toolbar.setTitle(<span class="string">&quot;&quot;</span>);</span><br><span class="line">        toolbar.setBackgroundColor(getResources().getColor(R.color.white));</span><br><span class="line">        setSupportActionBar(toolbar);</span><br><span class="line">        ImageView back = findViewById(R.id.toolbar_back_left);</span><br><span class="line">        back.setOnClickListener(<span class="keyword">new</span> View.OnClickListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onClick</span><span class="params">(View v)</span> </span>&#123;</span><br><span class="line">                finish();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        ImageView scale = findViewById(R.id.toolbar_icon_msg);</span><br><span class="line">        scale.setImageResource(R.mipmap.icon_web_scale);</span><br><span class="line">        scale.setVisibility(View.VISIBLE);</span><br><span class="line">        scale.setOnClickListener(<span class="keyword">new</span> View.OnClickListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onClick</span><span class="params">(View v)</span> </span>&#123;</span><br><span class="line">                isCanScale = !isCanScale;</span><br><span class="line">                <span class="keyword">if</span> (isCanScale)&#123;</span><br><span class="line">                    ((ImageView)v).setImageResource(R.mipmap.icon_web_scalable);</span><br><span class="line">                    mWebView.getSettings().setSupportZoom(<span class="keyword">true</span>); <span class="comment">//支持缩放，默认为true。是下面那个的前提。</span></span><br><span class="line">                    mWebView.getSettings().setBuiltInZoomControls(<span class="keyword">true</span>); <span class="comment">//设置内置的缩放控件。若为false，则该WebView不可缩</span></span><br><span class="line">                &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                    ((ImageView)v).setImageResource(R.mipmap.icon_web_scale);</span><br><span class="line">                    mWebView.getSettings().setSupportZoom(<span class="keyword">false</span>); <span class="comment">//支持缩放，默认为true。是下面那个的前提。</span></span><br><span class="line">                    mWebView.getSettings().setBuiltInZoomControls(<span class="keyword">false</span>); <span class="comment">//设置内置的缩放控件。若为false，则该WebView不可缩</span></span><br><span class="line">                &#125;</span><br><span class="line">                loadH5();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        mToolbarTitle = findViewById(R.id.toolbar_title);</span><br><span class="line">        mToolbarTitle.setTextColor(getResources().getColor(R.color.text_black));</span><br><span class="line">        mToolbarTitle.setTextSize(<span class="number">16.0f</span>);</span><br><span class="line">        mToolbarTitle.setText(<span class="string">&quot;详情&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        mContentLayout = findViewById(R.id.h5_content_layout);</span><br><span class="line">        LinearLayout.LayoutParams params = <span class="keyword">new</span> LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);</span><br><span class="line">        mWebView = <span class="keyword">new</span> WebView(<span class="keyword">this</span>.getApplicationContext());</span><br><span class="line">        mWebView.setLayoutParams(params);</span><br><span class="line">        mContentLayout.addView(mWebView);</span><br><span class="line">        buildWebView();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initData</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (getIntent() == <span class="keyword">null</span>)&#123;</span><br><span class="line">            finish();</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        mUrlStr = getIntent().getStringExtra(KEY_H5_URL);</span><br><span class="line">        <span class="keyword">if</span> ( TextUtils.isEmpty(mUrlStr) || <span class="string">&quot;null&quot;</span>.equals(mUrlStr) )&#123;</span><br><span class="line">            finish();</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        loadH5();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">loadH5</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (TextUtils.isEmpty(mUrlStr))&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        mWebView.loadDataWithBaseURL(<span class="keyword">null</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;text/html&quot;</span>, <span class="string">&quot;utf-8&quot;</span>, <span class="keyword">null</span>);</span><br><span class="line">        mWebView.clearHistory();</span><br><span class="line">        mWebView.clearCache(<span class="keyword">true</span>);</span><br><span class="line">        mWebView.loadUrl(mUrlStr);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">buildWebView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        mWebView.setWebChromeClient(<span class="keyword">new</span> WebChromeClient()&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedTitle</span><span class="params">(WebView view, String title)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">if</span> (!TextUtils.isEmpty(title))&#123;</span><br><span class="line">                    <span class="keyword">if</span> (title.length()&lt;<span class="number">6</span>)&#123;</span><br><span class="line">                        mToolbarTitle.setText(title);</span><br><span class="line">                    &#125;<span class="keyword">else</span> <span class="keyword">if</span> (title.length()&gt;<span class="number">10</span>)&#123;</span><br><span class="line">                        mToolbarTitle.setTextSize(<span class="number">12f</span>);</span><br><span class="line">                        title = title.substring(<span class="number">0</span>,<span class="number">8</span>);</span><br><span class="line">                        title = title + <span class="string">&quot;...&quot;</span>;</span><br><span class="line">                        mToolbarTitle.setText(title);</span><br><span class="line">                    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                        mToolbarTitle.setTextSize(<span class="number">14f</span>);</span><br><span class="line">                        mToolbarTitle.setText(title);</span><br><span class="line"></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) &#123;</span><br><span class="line">            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);</span><br><span class="line">            mWebView.setWebViewClient(<span class="keyword">new</span> WebViewClient() &#123;</span><br><span class="line">                <span class="meta">@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)</span></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, WebResourceRequest request)</span> </span>&#123;</span><br><span class="line">                    view.loadUrl(String.valueOf(request.getUrl()), request.getRequestHeaders());</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedSslError</span><span class="params">(WebView view, SslErrorHandler handler, SslError error)</span> </span>&#123;</span><br><span class="line">                    handler.proceed();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageStarted</span><span class="params">(WebView view, String url, Bitmap favicon)</span> </span>&#123;</span><br><span class="line">                    showLoading();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageFinished</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                    dismissLoading();</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            mWebView.setWebViewClient(<span class="keyword">new</span> WebViewClient() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                    view.loadUrl(url);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceivedSslError</span><span class="params">(WebView view, SslErrorHandler handler, SslError error)</span> </span>&#123;</span><br><span class="line">                    handler.proceed();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageStarted</span><span class="params">(WebView view, String url, Bitmap favicon)</span> </span>&#123;</span><br><span class="line">                    showLoading();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageFinished</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                    dismissLoading();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置</span></span><br><span class="line">        WebSettings webSettings = mWebView.getSettings();</span><br><span class="line">        <span class="comment">//设置支持Javascript</span></span><br><span class="line">        webSettings.setJavaScriptEnabled(<span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">//设置自适应</span></span><br><span class="line">        webSettings.setUseWideViewPort(<span class="keyword">true</span>); <span class="comment">//将图片调整到适合webview的大小</span></span><br><span class="line">        webSettings.setLoadWithOverviewMode(<span class="keyword">true</span>); <span class="comment">// 缩放至屏幕的大小</span></span><br><span class="line">        <span class="comment">//缩放</span></span><br><span class="line">        webSettings.setSupportZoom(<span class="keyword">true</span>); <span class="comment">//支持缩放，默认为true。是setBuiltInZoomControls(true)的前提。</span></span><br><span class="line">        webSettings.setBuiltInZoomControls(<span class="keyword">true</span>); <span class="comment">//设置内置的缩放控件。若为false=不可缩放</span></span><br><span class="line">        webSettings.setDisplayZoomControls(<span class="keyword">false</span>); <span class="comment">//隐藏原生的缩放控件</span></span><br><span class="line">        <span class="comment">//其他细节操作</span></span><br><span class="line">        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); </span><br><span class="line">        <span class="comment">//缓存模式如下：</span></span><br><span class="line">        <span class="comment">//LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据</span></span><br><span class="line">        <span class="comment">//LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。</span></span><br><span class="line">        <span class="comment">//LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.</span></span><br><span class="line">        <span class="comment">//LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。</span></span><br><span class="line">        webSettings.setAllowFileAccess(<span class="keyword">true</span>);<span class="comment">//可以访问文件</span></span><br><span class="line">        webSettings.setDomStorageEnabled(<span class="keyword">true</span>);<span class="comment">// 开启DOM storage</span></span><br><span class="line">        webSettings.setDatabaseEnabled(<span class="keyword">true</span>);<span class="comment">//开启database storage</span></span><br><span class="line">        webSettings.setAppCacheEnabled(<span class="keyword">true</span>);<span class="comment">//开启Application Caches</span></span><br><span class="line">        </span><br><span class="line">        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;</span><br><span class="line">        webSettings.setAppCachePath(cacheDirPath);<span class="comment">//设置Caches缓存目录</span></span><br><span class="line">        <span class="comment">//每个 Application 只调用一次 WebSettings.setAppCachePath()，WebSettings.setAppCacheMaxSize()</span></span><br><span class="line">        webSettings.setJavaScriptCanOpenWindowsAutomatically(<span class="keyword">true</span>); <span class="comment">//通过JS打开新窗口</span></span><br><span class="line">        webSettings.setLoadsImagesAutomatically(<span class="keyword">true</span>); <span class="comment">//自动加载图片</span></span><br><span class="line">        webSettings.setDefaultTextEncodingName(<span class="string">&quot;utf-8&quot;</span>);<span class="comment">//设置编码格式</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">showLoading</span><span class="params">()</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">destoryWebView</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (mWebView != <span class="keyword">null</span>) &#123;</span><br><span class="line">            mWebView.loadDataWithBaseURL(<span class="keyword">null</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;text/html&quot;</span>, <span class="string">&quot;utf-8&quot;</span>, <span class="keyword">null</span>);</span><br><span class="line">            mWebView.clearHistory();</span><br><span class="line">            mWebView.clearCache(<span class="keyword">true</span>);</span><br><span class="line">            ((ViewGroup) mWebView.getParent()).removeView(mWebView);</span><br><span class="line">            mWebView.destroy();</span><br><span class="line">            mWebView = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dismissLoading</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setAndroidNativeLightStatusBar</span><span class="params">(Activity activity, <span class="keyword">boolean</span> dark)</span> </span>&#123;</span><br><span class="line">        View decor = activity.getWindow().getDecorView();</span><br><span class="line">        <span class="keyword">if</span> (dark) &#123;</span><br><span class="line">            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre>

<h1 id="5-完整代码-，copy即用"><a href="#5-完整代码-，copy即用" class="headerlink" title="5.完整代码 ，copy即用"></a>5.完整代码 ，copy即用</h1><blockquote>
<p>github: <a target="_blank" rel="noopener" href="https://github.com/Cupster/OneDayOneView/tree/master/webview">https://github.com/Cupster/OneDayOneView/tree/master/webview</a></p>
</blockquote>
<hr>
<p>感谢：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://me.csdn.net/lmj623565791">鸿洋_</a>、<a target="_blank" rel="noopener" href="https://me.csdn.net/sinyu890807">郭霖</a>、<a target="_blank" rel="noopener" href="https://me.csdn.net/carson_ho">Carson_Ho</a>、<a target="_blank" rel="noopener" href="https://me.csdn.net/aqi00">aqi00</a> 等大神</p>
</blockquote>

  </div>
  <div>
  
  <div class="post-note note-warning copyright" style="margin-top: 42px">
    <p><span style="font-weight: bold;">作者：</span><a target="_blank" rel="nofollow noopener noreferrer" href="http://example.com/about">Cupster</a></p>
    <p><span style="font-weight: bold;">文章链接：</span><a target="_blank" rel="nofollow noopener noreferrer" href="http://example.com/2020/12/03/WebView%E5%AE%8C%E6%95%B4%E9%85%8D%E7%BD%AE%E5%8F%8A%E6%AD%A3%E7%A1%AE%E4%BD%BF%E7%94%A8%EF%BC%8C%E6%8A%A0%E9%97%A8%E5%BC%8F%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E6%8E%A7/">http://example.com/2020/12/03/WebView%E5%AE%8C%E6%95%B4%E9%85%8D%E7%BD%AE%E5%8F%8A%E6%AD%A3%E7%A1%AE%E4%BD%BF%E7%94%A8%EF%BC%8C%E6%8A%A0%E9%97%A8%E5%BC%8F%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E6%8E%A7/</a></p>
    <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
  </div>
  
  </div>
</article>
<div class="nav">
  
  <div class="nav-item-prev">
    <a href="/2021/01/06/ConstraintLayout详解/" class="nav-link">
      <i class="iconfont icon-left nav-prev-icon"></i>
      <div>
        <div class="nav-label">上一篇</div>
        
        <div class="nav-title">ConstraintLayout详解 </div>
        
      </div>
    </a>
  </div>
  
  
  <div class="nav-item-next">
    <a href="/2020/11/26/MacOS 13.6 Scrcpy安装失败问题解决/" class="nav-link">
      <div>
        <div class="nav-label">下一篇</div>
        
        <div class="nav-title">MacOS 13.6 Scrcpy安装失败问题解决 </div>
        
      </div>
      <i class="iconfont icon-right nav-next-icon"></i>
    </a>
  </div>
  
</div>

<div class="card card-content toc-card" id="mobiletoc">
  <div class="toc-header"><i class="iconfont icon-menu" style="padding-right: 2px;"></i>目录</div>
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E8%A6%81%E7%82%B9"><span class="toc-text">1.要点</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8"><span class="toc-text">2.使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1%E5%B8%83%E5%B1%80%E6%96%87%E4%BB%B6"><span class="toc-text">2.1布局文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2Java%E4%BB%A3%E7%A0%81%E6%B7%BB%E5%8A%A0WebView"><span class="toc-text">2.2Java代码添加WebView</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E6%8E%A7%E5%88%B6%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%EF%BC%8C%E9%98%B2%E6%AD%A2%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">2.3 控制生命周期，防止内存泄漏</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-%E9%87%8D%E7%82%B9%EF%BC%9AWebView-%E9%85%8D%E7%BD%AE"><span class="toc-text">2.4 重点：WebView 配置</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E5%85%B6%E4%BB%96%E7%BB%86%E8%8A%82%E4%BB%A3%E7%A0%81"><span class="toc-text">3.其他细节代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-%E5%AE%8C%E6%95%B4Activity%E4%BB%A3%E7%A0%81"><span class="toc-text">4.完整Activity代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81-%EF%BC%8Ccopy%E5%8D%B3%E7%94%A8"><span class="toc-text">5.完整代码 ，copy即用</span></a></li></ol>
</div></main>
          <aside class="left-column">
            
            <div class="card card-author">
              
<img src="/img/ic_head.jpg" class="author-img">

<p class="author-name">Cupster</p>
<p class="author-description">深山磨柴斧，一鸣震江湖</p>
<div class="author-message">
  <a class="author-posts-count" href="/archives">
    <span>66</span>
    <span>文章</span>
  </a>
  <a class="author-categories-count" href="/categories">
    <span>5</span>
    <span>分类</span>
  </a>
  <a class="author-tags-count" href="/tags">
    <span>31</span>
    <span>标签</span>
  </a>
</div>

<div class="author-card-society">
  
    <div class="author-card-society-icon">
      <a target="_blank" rel="noopener" href="https://cupster.blog.csdn.net/">
        <i class="iconfont /img/ic_csdn.png society-icon"></i>
      </a>
    </div>
  
</div>

            </div>
            
            <div class="sticky-tablet">
  
  
  <article class="display-when-two-columns spacer">
    <div class="card card-content toc-card">
      <div class="toc-header"><i class="iconfont icon-menu" style="padding-right: 2px;"></i>目录</div>
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E8%A6%81%E7%82%B9"><span class="toc-text">1.要点</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8"><span class="toc-text">2.使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1%E5%B8%83%E5%B1%80%E6%96%87%E4%BB%B6"><span class="toc-text">2.1布局文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2Java%E4%BB%A3%E7%A0%81%E6%B7%BB%E5%8A%A0WebView"><span class="toc-text">2.2Java代码添加WebView</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E6%8E%A7%E5%88%B6%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%EF%BC%8C%E9%98%B2%E6%AD%A2%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">2.3 控制生命周期，防止内存泄漏</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-%E9%87%8D%E7%82%B9%EF%BC%9AWebView-%E9%85%8D%E7%BD%AE"><span class="toc-text">2.4 重点：WebView 配置</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E5%85%B6%E4%BB%96%E7%BB%86%E8%8A%82%E4%BB%A3%E7%A0%81"><span class="toc-text">3.其他细节代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-%E5%AE%8C%E6%95%B4Activity%E4%BB%A3%E7%A0%81"><span class="toc-text">4.完整Activity代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81-%EF%BC%8Ccopy%E5%8D%B3%E7%94%A8"><span class="toc-text">5.完整代码 ，copy即用</span></a></li></ol>
    </div>
  </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header"><i class="iconfont icon-fenlei" style="padding-right: 2px;"></i>分类</div>
  <div class="categories-list">
    
      <a href="/categories/Android/">
        <div class="categories-list-item">
          Android
          <span class="categories-list-item-badge">38</span>
        </div>
      </a>
    
      <a href="/categories/Linux/">
        <div class="categories-list-item">
          Linux
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Dev-Base/">
        <div class="categories-list-item">
          Dev-Base
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/Kotlin/">
        <div class="categories-list-item">
          Kotlin
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/自动化脚本/">
        <div class="categories-list-item">
          自动化脚本
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header"><i class="iconfont icon-biaoqian" style="padding-right: 2px;"></i>热门标签</div>
  <div class="tags-list">
    
    <a href="/tags/Android/" title="Android"><div class="tags-list-item">Android</div></a>
    
    <a href="/tags/Android自定义View/" title="Android自定义View"><div class="tags-list-item">Android自定义View</div></a>
    
    <a href="/tags/MacOS/" title="MacOS"><div class="tags-list-item">MacOS</div></a>
    
    <a href="/tags/Kotlin/" title="Kotlin"><div class="tags-list-item">Kotlin</div></a>
    
    <a href="/tags/Android持久化/" title="Android持久化"><div class="tags-list-item">Android持久化</div></a>
    
    <a href="/tags/CentOS/" title="CentOS"><div class="tags-list-item">CentOS</div></a>
    
    <a href="/tags/Linux/" title="Linux"><div class="tags-list-item">Linux</div></a>
    
    <a href="/tags/Android事件/" title="Android事件"><div class="tags-list-item">Android事件</div></a>
    
    <a href="/tags/Android基础/" title="Android基础"><div class="tags-list-item">Android基础</div></a>
    
    <a href="/tags/Android手势/" title="Android手势"><div class="tags-list-item">Android手势</div></a>
    
    <a href="/tags/Scrcpy/" title="Scrcpy"><div class="tags-list-item">Scrcpy</div></a>
    
    <a href="/tags/Android动画/" title="Android动画"><div class="tags-list-item">Android动画</div></a>
    
    <a href="/tags/Git/" title="Git"><div class="tags-list-item">Git</div></a>
    
    <a href="/tags/Java/" title="Java"><div class="tags-list-item">Java</div></a>
    
    <a href="/tags/Docker/" title="Docker"><div class="tags-list-item">Docker</div></a>
    
    <a href="/tags/Android-Dialog/" title="Android Dialog"><div class="tags-list-item">Android Dialog</div></a>
    
  </div>
</div>
  </article>
  
  
</div>
          </aside>
          <aside class="right-column">
            <div class="sticky-widescreen">
  
  
  <article class="card card-content toc-card">
    <div class="toc-header"><i class="iconfont icon-menu" style="padding-right: 2px;"></i>目录</div>
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E8%A6%81%E7%82%B9"><span class="toc-text">1.要点</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8"><span class="toc-text">2.使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1%E5%B8%83%E5%B1%80%E6%96%87%E4%BB%B6"><span class="toc-text">2.1布局文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2Java%E4%BB%A3%E7%A0%81%E6%B7%BB%E5%8A%A0WebView"><span class="toc-text">2.2Java代码添加WebView</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E6%8E%A7%E5%88%B6%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%EF%BC%8C%E9%98%B2%E6%AD%A2%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">2.3 控制生命周期，防止内存泄漏</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-%E9%87%8D%E7%82%B9%EF%BC%9AWebView-%E9%85%8D%E7%BD%AE"><span class="toc-text">2.4 重点：WebView 配置</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E5%85%B6%E4%BB%96%E7%BB%86%E8%8A%82%E4%BB%A3%E7%A0%81"><span class="toc-text">3.其他细节代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-%E5%AE%8C%E6%95%B4Activity%E4%BB%A3%E7%A0%81"><span class="toc-text">4.完整Activity代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81-%EF%BC%8Ccopy%E5%8D%B3%E7%94%A8"><span class="toc-text">5.完整代码 ，copy即用</span></a></li></ol>
  </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header"><i class="iconfont icon-wenzhang_huaban" style="padding-right: 2px;"></i>最近文章</div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2021-03-02</div>
        <a href="/2021/03/02/Git commit规范/"><div class="recent-posts-item-content">Git commit规范</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2021-02-16</div>
        <a href="/2021/02/16/AutoJS一文精通AutoJS脚本教程详解/"><div class="recent-posts-item-content">AutoJS一文精通AutoJS脚本教程详解</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2021-01-21</div>
        <a href="/2021/01/21/架构师进阶：注解Annotation全解/"><div class="recent-posts-item-content">架构师进阶：注解Annotation全解</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2021-01-06</div>
        <a href="/2021/01/06/ConstraintLayout详解/"><div class="recent-posts-item-content">ConstraintLayout详解</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
          </aside>
        </div>
      </div>
    </div>
  </div>
  
  <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>Copyright ©
          
          2020 -
          
          2021
        </span>
        &nbsp;
        <a href="/" class="footer-link">不负明天 </a>
      </div>
    </div>

    
    <div class="footer-dsc">
      
      Powered by
      <a href="https://hexo.io/" class="footer-link" target="_blank" rel="nofollow noopener noreferrer">&nbsp;Hexo </a>
      
      
      <span>&nbsp;|&nbsp;</span>
      
      
      Theme -
      <a href="https://github.com/theme-kaze" class="footer-link" target="_blank"
        rel="nofollow noopener noreferrer">&nbsp;Kaze</a>
      
    </div>
    
    
    
    
      <div class="footer-dsc">
        
        本站总访问量686<span id="busuanzi_value_site_pv"></span>次
        
        
        <span>&nbsp;|&nbsp;</span>
        
        
        本站总访客数219<span id="busuanzi_value_site_uv"></span>次
        
      </div>
      
    
</footer>
  <a role="button" id="scrollbutton" class="basebutton"  aria-label="回到顶部">
  <i class="iconfont icon-arrowleft button-icon"></i>
</a>
<a role="button" id="menubutton" class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a role="button" id="popbutton" class="basebutton" aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a role="button" id="darkbutton" class="basebutton darkwidget" aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a role="button" id="searchbutton" class="basebutton searchwidget" aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a>

  
  
  
  <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img');
    var i;
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a');
      wrapper.setAttribute('href', img[i].getAttribute('data-src'));
      wrapper.setAttribute('aria-label', 'illustration');
      wrapper.style.cssText = 'width: 100%; display: flex; justify-content: center;';
      if (img[i].alt) wrapper.dataset.caption = img[i].alt;
      wrapper.dataset.nolink = true;
      img[i].before(wrapper);
      wrapper.append(img[i]);
      var divWrap = document.createElement('div');
      divWrap.classList.add('gallery');
      wrapper.before(divWrap);
      divWrap.append(wrapper);
    }
    baguetteBox.run('.gallery');
  }
</script>
<script>loadScript("/js/lib/lightbox/baguetteBox.min.js", addImgLayout)</script>
  
  
  
<script src="/js/main.js"></script>

  
  <script>loadScript("/js/lib/busuanzi.min.js")</script>
  
  
  <script>
    var addLazyload = function () {
      var observer = lozad('.lozad', {
        load: function (el) {
          el.srcset = el.getAttribute('data-src');
        },
        loaded: function (el) {
          el.classList.add('loaded');
        }
      });
      observer.observe();
    }
  </script>
  <script>loadScript("/js/lib/lozad.min.js", addLazyload)</script>
  
  
</body>

</html>